08. Exercise: Override onSizeChanged()
22 07 AAK OnSizeChanged SC
Android Developer Documentation
Exercise
In this exercise you are going to override onSizeChanged().
- In
MyCanvasView, at the class level, define member variables for a canvas and a bitmap. Call themextraCanvasandextraBitmap. These are your bitmap and canvas for caching what has been drawn before.
private lateinit var extraCanvas: Canvas
private lateinit var extraBitmap: Bitmap
- Define a class level variable
backgroundColor, for the background color of the canvas and initialize it to thecolorBackgroundyou defined earlier.
private val backgroundColor = ResourcesCompat.getColor(resources, R.color.colorBackground, null)
- In
MyCanvasView, override theonSizeChanged()method. This callback method is called by the Android system with the changed screen dimensions, that is, with a new width and height (to change to) and the old width and height (to change from).
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidth, oldHeight)
}
- Inside
onSizeChanged(), create an instance ofBitmapwith the new width and height, which are the screen size, and assign it toextraBitmap. The third argument is the bitmap color configuration.ARGB_8888stores each color in 4 bytes and is recommended.
extraBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
- Create a
Canvasinstance fromextraBitmapand assign it toextraCanvas.
extraCanvas = Canvas(extraBitmap)
- Specify the background color in which to fill
extraCanvas.
extraCanvas.drawColor(backgroundColor)
- Looking at
onSizeChanged(), a new bitmap and canvas are created every time the function executes. You need a new bitmap, because the size has changed. However, this is a memory leak, leaving the old bitmaps around. To fix this, recycleextraBitmapbefore creating the next one.
if (::extraBitmap.isInitialized) extraBitmap.recycle()